import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import cross_val_score
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import sys
import os
sys.path.append(os.getcwd())
from data_process.data_process_adfa import process_adfa
import random
from metric.metric_class import metric_oneclass
from sklearn.model_selection import RandomizedSearchCV,GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeClassifier
import codecs
import csv
def get_vector_adfa(txt_list,type):
    if type=='word2_vec_means':
        data_adfa=process_adfa(setpath=adfa_path)
        word2vec_list=data_adfa.get_word2vec(txt_list,model_path=None,vector_size=100)
        txt_vector=[]
        for sentence in word2vec_list:
            txt_vector.append(np.mean(sentence,axis=0))
        txt_vector=np.array(txt_vector)

    if type=='wordbagvector':
        data_adfa = process_adfa(setpath=adfa_path)
        txt_vector = data_adfa.get_wordsbag_Vector(txt_list, vector='count', ngram_range=(2,3), min_df=1)
    if type=='doc2vec':
        data_adfa = process_adfa(setpath=adfa_path)
        txt_vector=data_adfa.get_doc2vec(txt_list,vector_size=10)
    return txt_vector


if __name__=="__main__":

    adfa_path='D:\database\ADFA-LD\ADFA-LD\ADFA-LD'
    data=process_adfa(setpath=adfa_path)
    traces_training,traces_validation,traces_attacks=data.get_txt()
    traces_attacksall=[]
    for types in traces_attacks:
        traces_attacksall=traces_attacksall+types
    print('训练集长度是'+str(len(traces_training))+'-'*20)
    print('验证集长度是'+str(len(traces_validation))+'-'*20)
    print('攻击集长度是'+str(len(traces_attacksall))+'-'*20)
    random.shuffle(traces_training)
    random.shuffle(traces_validation)
    random.shuffle(traces_attacksall)
    train_x=traces_training+traces_attacksall
    test_x=traces_validation[:746]+traces_attacksall
    train_y=[0 for i in range(833)]+[1 for i in range(746)]
    test_y=[0 for i in range(746)]+[1 for i in range(746)]
    train_vector=get_vector_adfa(train_x,type='wordbagvector')
    test_vector=get_vector_adfa(test_x,type='wordbagvector')
    
    # clf = RandomForestRegressor(n_estimators=100)
    clf=DecisionTreeClassifier()
   
    clf.fit(train_vector,train_y)
    
    # best_estimator.fit(train_vector,train_y)
    y_pre = clf.predict(test_vector)
    num=0
    for i in range(len(y_pre)):
        if abs(y_pre[i]-test_y[i])<=0.5:
            num+=1
    print(num/len(y_pre))
    # metric=metric_oneclass(y_pre,test_y)
    # acc = metric.acc()
    # print(acc)

    f = codecs.open(r'C:/Users/Administrator/Desktop/我的投稿/实验数据/DecisionTree.csv', 'w', encoding='utf-8')
    writer = csv.writer(f)
    writer.writerow(['real', 'predict'])
    for i in range(len(test_y)):
        writer.writerow([str(test_y[i]), str(y_pre[i])])
    f.close()